package org.rqb.panel.partPanel;

import lombok.extern.slf4j.Slf4j;
import org.rqb.Constant;
import org.rqb.utils.HttpUtil;

import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutionException;

import static org.rqb.Constant.AD_BTN_TEXT;
import static org.rqb.Constant.AD_BTN_TEXT_HID;

@Slf4j
public class AdPanel extends JPanel implements ActionListener {

    private JButton dropDownBtn;
    private boolean isExpanded = false; // 标记是否已经展开
    private JPanel imagePanel; // 展示图片的Panel
    private JLabel hidLabel;

    private int targetImageWidth = 260;
    private int targetImageHeight = 250;

    public AdPanel() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(Constant.AD_WIDTH, Constant.AD_BTN_HEIGHT));  // 初始高度设为100
        this.setBackground(Color.LIGHT_GRAY);

        // 初始化下拉框按钮
        btnInit();
        //广告面板图片加载初始化
        imagePanelInit();

        this.add(dropDownBtn, BorderLayout.NORTH); // 初始状态按钮在上方

    }

    private void imagePanelInit() {

        imagePanel = new JPanel();
        imagePanel.setLayout(new GridLayout(2, 2)); // 假设用网格布局展示图片
        // 添加一些示例图片
        addImagesToPanel(imagePanel);
        imagePanel.setVisible(false);
        this.add(imagePanel, BorderLayout.CENTER); // 图片panel放在中间，初始不可见
    }

    private void btnInit() {
        dropDownBtn = new JButton(AD_BTN_TEXT);
        hidLabel = new JLabel(AD_BTN_TEXT_HID);
        hidLabel.setHorizontalAlignment(SwingConstants.CENTER);
        dropDownBtn.setBackground(Color.LIGHT_GRAY);

        dropDownBtn.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == dropDownBtn) {
            togglePanel();

        }
    }
    private void togglePanel() {
        this.remove(dropDownBtn); // 先移除按钮
        if (isExpanded) {
            // 收起面板
            this.remove(hidLabel);
            this.setPreferredSize(new Dimension(Constant.AD_WIDTH, Constant.AD_BTN_HEIGHT)); // 恢复原始高度
            imagePanel.setVisible(false);
            this.add(dropDownBtn, BorderLayout.NORTH); // 按钮移到上方
        } else {

            // 展开面板
            this.add(hidLabel,BorderLayout.NORTH);
            this.setPreferredSize(new Dimension(Constant.AD_WIDTH, Constant.AD_BTN_HEIGHT)); // 展开高度
            imagePanel.setVisible(true);
            this.add(dropDownBtn, BorderLayout.SOUTH); // 按钮移到底部
        }

        isExpanded = !isExpanded;

        revalidate(); // 重新布局
        repaint();    // 重新绘制
    }

    /**
     * 处理图片缩放问题
     * @param originalImage
     * @return
     */
    private BufferedImage scaleImage(BufferedImage originalImage) {
        // 创建目标图像（画布）
        BufferedImage bufferedImage = new BufferedImage(targetImageWidth, targetImageHeight, BufferedImage.TYPE_INT_RGB);
        // 获取绘图对象
        Graphics2D g2d = bufferedImage.createGraphics();
        // 计算等比缩放尺寸
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();
        double ratio = Math.min((double) targetImageWidth / originalWidth, (double) targetImageHeight / originalHeight);
        int newWidth = (int) (originalWidth * ratio);
        int newHeight = (int) (originalHeight * ratio);

        // 计算居中位置
        int x = (targetImageWidth - newWidth) / 2;
        int y = (targetImageHeight - newHeight) / 2;

        // 绘制缩放后的图片到画布中
        g2d.drawImage(originalImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), x, y, null);
        // 清理资源
        g2d.dispose();
        return bufferedImage;

    }

    private void addImagesToPanel(JPanel imagePanel) {
        new SwingWorker<List<ImageIcon>, Void>() {
            private Map<String,String> commodityMap = Constant.commodityMap;
            @Override
            protected List<ImageIcon> doInBackground() throws Exception {
                ArrayList<ImageIcon> imageIcons = new ArrayList<>();
                Iterator<Map.Entry<String, String>> iterator = commodityMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> entry = iterator.next();
                    imageIcons.add(new ImageIcon(Objects.requireNonNull(getClass().getClassLoader().getResource(entry.getKey())), entry.getValue()));
                }

                return imageIcons;
            }

            @Override
            protected void done() {
                try {
                    List<ImageIcon> imageIconList = get();
                    imagePanel.removeAll();
                    for (int i = 0; i < imageIconList.size(); i++) {
                        ImageIcon icon = imageIconList.get(i);
                        String imageUrl = icon.getDescription(); //url

                        JLabel label = new JLabel(icon);
                        label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                        label.setToolTipText("点击打开：" + imageUrl);

                        // 🟢 点击图片打开浏览器
                        label.addMouseListener(new MouseAdapter() {
                            @Override
                            public void mouseClicked(MouseEvent e) {
                                if (Desktop.isDesktopSupported()) {
                                    try {
                                        Desktop.getDesktop().browse(new URI(imageUrl));
                                    } catch (Exception ex) {
                                        log.error("无法打开浏览器：" + ex.getMessage());
                                    }
                                } else {
                                    log.warn("当前系统不支持 Desktop API");
                                }
                            }
                        });

                        imagePanel.add(label);
                    }

                    imagePanel.revalidate();
                    imagePanel.repaint();

                } catch (InterruptedException | ExecutionException e) {
                    log.error("读取广告失败：" + e.getMessage());
                }
            }
        }.execute();
    }


}
